package com.runmonk.core.util;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

/**
 * @author chaobo
 * @since 2019/3/21
 */
public class HttpServletResponseUtil {
    private static Logger LOGGER = LoggerFactory.getLogger(HttpServletResponseUtil.class);

    public static void buildAttachResponseInfo(File outFile, HttpServletResponse response) throws IOException {
        response.setContentLength((int) outFile.length());
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-type", "application/pdf;charset=utf-8");

        String filename = outFile.getName();

        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("response Content-Disposition error = {}", e);
        }

        //java7 try-with-resources 写法,不需要finally 关闭
        try (FileInputStream in = new FileInputStream(outFile)) {
            try (OutputStream out = response.getOutputStream()) {
                byte[] b = new byte[2048];
                while ((in.read(b)) != -1) {
                    out.write(b);
                }
            }
        }
    }
}
